#include "Comm.hh"

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

// client tcp 127.0.0.1 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " ip port" << std::endl;
        return 1;
    }
    // server IP
    std::string server_ip = argv[1]; // 点分十进制的字符串风格的IP地址
    // server port
    int server_port = atoi(argv[2]);

    // create socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket failed" << std::endl;
        return 2;
    }
    // client不需要显示的bind,TCP是面相连接的，所需需要先连接才能访问服务器
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_addr.s_addr = inet_addr(server_ip.c_str()); // 这个接口不安全
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);

    // 首次连接，connect底层会自动进行bind
    int n = ::connect(sockfd, CONV(&server), sizeof(server));
    if (n < 0)
    {
        std::cout << "connect failed " << std::endl;
        return 3;
    }
    // 连接成功，进行通信

    std::string mesasge;
    while(true)
    {
        char inbuffer[1024];
        std::cout << "input message: ";
        std::getline(std::cin,mesasge);

        //write成功返回写入多少字节
        n = ::send(sockfd,mesasge.c_str(),mesasge.size(),0);
        if(n > 0)
        {
            int m = ::recv(sockfd,inbuffer,sizeof(inbuffer),0);
            if(m > 0)
            {
                inbuffer[m] = 0;
                std::cout << inbuffer << std::endl;
            }
            else 
            {
                break;
            }
        }
        else 
        {
            break;
        }
    }
    ::close(sockfd);
    return 0;
}